package com.haoze.nurseapp.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.haoze.common.dto.PushSocketMessage;
import com.haoze.common.dto.SocketMessageDTO;
import com.haoze.common.enumeration.StateEnum;
import com.haoze.common.model.TaskExecuteBatchEntity;
import com.haoze.common.response.Result;
import com.haoze.common.response.ResultGenerator;
import com.haoze.common.utils.HttpClientUtil;
import com.haoze.common.utils.JSONUtils;
import com.haoze.common.utils.UUIDUtil;
import com.haoze.nurseapp.dao.MealListMapper;
import com.haoze.nurseapp.dao.SpecimenMapper;
import com.haoze.nurseapp.dao.TaskExecuteMapper;
import com.haoze.nurseapp.dao.UserMapper;
import com.haoze.nurseapp.dto.PatientLabReportDTO;
import com.haoze.nurseapp.dto.SpecimenTransferDTO;
import com.haoze.nurseapp.dto.specimen.SpecimenReadyDto;
import com.haoze.nurseapp.dto.task.TaskExecuteBatchDTO;
import com.haoze.nurseapp.enumeration.SpecialNodeEnum;
import com.haoze.nurseapp.enumeration.SpecimenFlowEnum;
import com.haoze.nurseapp.model.*;
import com.haoze.nurseapp.service.*;
import com.haoze.nurseapp.service.feign.PatientOrderService;
import com.haoze.nurseapp.vo.EmrFile;
import com.haoze.nurseapp.vo.OrderInfo;
import com.haoze.nurseapp.vo.PatientInfo;
import com.haoze.nurseapp.vo.TaskNodeVO;
import com.haoze.nurseapp.vo.specimen.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.net.ssl.SNIMatcher;
import java.sql.Timestamp;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wangze
 * @date 2020-05-20 13:19.
 **/
@Service
public class SpecimenServiceImpl implements SpecimenService {

	private static final Logger logger = LoggerFactory.getLogger(SpecimenServiceImpl.class);

	@Resource
	private SpecimenMapper specimenMapper;

	@Resource
	NurseFileIndexService fileIndexService;

	@Resource
	NursePatientOrderService patientOrderService;

	@Resource
	PatientService patientService;
	@Resource
	NurseFileIndexService nurseFileIndexService;
	@Resource
	OrderService orderService;
	@Resource
	TaskExecuteMapper taskExecuteMapper;
	@Resource
	UserMapper userMapper;

	@Autowired
	private PasswordEncoder passwordEncoder;

	@Value("${socket.nurseUrl}")
	//private String socketUrl = "http://172.30.100.210:8100/push/nurseUser";
	private String socketUrl;

	@Autowired
	private MealListMapper mealListMapper;


	/**
	 * 一个标本对应多个任务，不同的标码，对应同一个组医嘱
	 * @param specimenNum
	 * @param showFlag
	 * @return
	 */
	@Override
	public SpecimenDetailVO querySpecimen(String specimenNum, String showFlag) {
		// 一个标本可能对应多个检验，这边只取一个
		SpecimenDetailVO specimenDetailVO = this.specimenMapper.querySepcimen(specimenNum);
		if (Objects.isNull(specimenDetailVO)) {
			return null;
		}
		// 获取节点状态
		List<SpecimenNodeInfoVO> nodeInfoVOs=getLatestNodeInfo(specimenNum);
		if (CollectionUtils.isEmpty(nodeInfoVOs)) {
			throw new RuntimeException(specimenNum+"未找到任务节点");
		}
		Map<String, String> patientMap = patientService.getPatientInfoWithComputeAge(specimenDetailVO.getInpatNum());
		specimenDetailVO.setPatientInfo(patientMap);
		specimenDetailVO.setNodeInfoVOs(nodeInfoVOs);
		// 一个标本条码对应多个任务，但是任务节点应该都是一样的，所以只取一个
		// 处理一个条码，对应多个任务 ,因为其他的和一样，所以只取第一个
		SpecimenNodeInfoVO  oneOneInfo=nodeInfoVOs.stream().filter(x->specimenDetailVO.getSeNum().equals(x.getSeNum())).findFirst().orElse(null);
		specimenDetailVO.setNodeId(specimenDetailVO.getNodeId());
		specimenDetailVO.setNodeName(oneOneInfo.getNodeName());
		specimenDetailVO.setNodeEnter(oneOneInfo.getNodeEnter());
		if(null != showFlag && showFlag.equals("0")){
			return specimenDetailVO;
		}
		//标本准备要获取文书
		if (SpecimenFlowEnum.SPECIMEN_READY.getNodeId().equals(oneOneInfo.getNodeId())) {
			//设置文书对应的值
			List<FileIndexValueVO> fileIndexValueVOList = this.specimenMapper.queryFileValue(specimenNum);
			for (int i = 0;i<fileIndexValueVOList.size();i++){
				FileIndexValueVO x = fileIndexValueVOList.get(i);
				//if(null!=x.getDataValue() && null != x.getVarCode() && x.getVarCode().equals("cell_color")){
				if(null != x.getVarCode() && x.getVarCode().equals("cell_color")){
					/*String color = Long.toHexString(Long.valueOf(x.getDataValue()));
					final int colorSize = 6;
					int size = color.length();
					if(size < colorSize){
						for (int y = 0; y < colorSize - size; y++){
							color += "0";
						}
					}*/
					String testTubeColor = specimenMapper.selectSysTestTubeColorBySpecimenNum(specimenNum);
					if(StringUtils.isNotBlank(testTubeColor)){
						x.setDataValue(testTubeColor);
					}
				}
			}
			specimenDetailVO.setFileIndexValue(fileIndexValueVOList);
			//设置当前节点的文书
			EmrFile emrFile = nurseFileIndexService.getFileIndex(oneOneInfo.getEmrFileId());
			specimenDetailVO.setEmrFile(emrFile);
		}
		return specimenDetailVO;
	}



	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result specimenReady(List<SpecimenReadyDto> readyDtos) {
		try{
			List<SpecimenNodeInfoVO> taskDetailList = executeNextNode(readyDtos.stream().map(x -> x.getSpecimenNum()).collect(Collectors.toList()), SpecimenFlowEnum.SPECIMEN_READY);
			for (SpecimenReadyDto readyDto : readyDtos) {
				if (readyDto.getEmrFile() != null && readyDto.getEmrFile().getEmrFileIndexEntity() != null) {
					fileIndexService.saveFileIndex(readyDto.getEmrFile());
				}
			}
			return specimenNodeChange(taskDetailList);
		}catch (Exception ex){
			return  ResultGenerator.genFailedResult(ex.getMessage());
		}
	}

	@Override
	public Result specimenTransfer(String specimen){
		return ResultGenerator.genOkResult();
	}



	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result specimenFinish(List<String> specimenNums) {
		try{
			List<SpecimenNodeInfoVO> nodeStatusList=executeNextNode(specimenNums,SpecimenFlowEnum.SPECIMEN_COLLECT);
			//TODO CESHI
			//String userId="bf533ba10ec64ab0bbf360c44fa7a787";
			return specimenNodeChange(nodeStatusList);
		}catch (Exception ex){
			return  ResultGenerator.genFailedResult(ex.getMessage());
		}

	}

	/**
	 * 标本节点状态变更
	 * @param nodeStatusList
	 * @return
	 */
	private Result specimenNodeChange(List<SpecimenNodeInfoVO> nodeStatusList) {
		//TODO CESHI
		//String userId="bf533ba10ec64ab0bbf360c44fa7a787";
		String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
		List<Map<String,Object>>   listMap=new ArrayList<>();
		for (SpecimenNodeInfoVO nodeInfoVO : nodeStatusList) {
			Map<String,Object> map= new HashMap<>();
			TaskExecuteBatchEntity ta=specimenMapper.queryMaxExecuteBatch(nodeInfoVO.getTaskExecuteDetailId());
			map.put("taskExecuteDetailEntity", ta);
			map.put("userId",userId);
			listMap.add(map);
		}
		patientOrderService.createNextTaskNodeList(listMap,"");
		return ResultGenerator.genOkResult();
	}

	/**
	 * 执行流程
	 *
	 * @param specimens
	 * @param specimenFlowEnum
	 * @return
	 */
	public List<SpecimenNodeInfoVO> executeNextNode(List<String> specimens, SpecimenFlowEnum specimenFlowEnum) {
		List<SpecimenNodeInfoVO> taskExecuteDetailIds = new ArrayList<>();
		for (String specimen : specimens) {
			// 获取所有的任务
			List<SpecimenNodeInfoVO> nodeInfoVOs = getLatestNodeInfo(specimen);
			for (SpecimenNodeInfoVO nodeInfoVO:nodeInfoVOs){
				if ("1".equals(nodeInfoVO.getStatus())) {
					logger.error("节点状态错误:" + specimen);
					throw new RuntimeException(specimen + "节点状态错误");
				}
				if (!specimenFlowEnum.getNodeId().equals(nodeInfoVO.getNodeId())) {
					logger.error("错误的标本:" + specimen);
					throw new RuntimeException(specimen + "在" + nodeInfoVO.getNodeName() + "阶段");
				}
				//判断task_detail_id 是否重复
				logger.info("task_detail_id的主键="+nodeInfoVO.getTaskExecuteDetailId());
				if(taskExecuteDetailIds.stream()
						.anyMatch(x->x.getTaskExecuteDetailId().equals(nodeInfoVO.getTaskExecuteDetailId()))){
					continue;
				}
				taskExecuteDetailIds.add(nodeInfoVO);
			}
		}
		return taskExecuteDetailIds;
	}

	/**
	 * 获取最新的节点状态信息
	 * @param specimen
	 * @return
	 */
	private List<SpecimenNodeInfoVO> getLatestNodeInfo(String specimen){
		//一个标本，可能对应多个医嘱
		List<SpecimenNodeInfoVO> specimenNodeResult=new ArrayList<>();
		List<SpecimenOrderVO> orderIds = this.specimenMapper.queryOrderIdsBySpecimen(specimen);
		if(CollectionUtils.isEmpty(orderIds)){
			logger.error("错误的标本号:"+specimen);
			throw new RuntimeException(specimen+"没有对应的医嘱");
		}
		for (SpecimenOrderVO orderInfo :orderIds){
			// 判断医嘱状态
			if(orderInfo.getCancelDatetime()!=null){
				logger.error("该医嘱已取消,错误的标本号:"+specimen);
				throw new RuntimeException("该医嘱已取消");
			}
			// 因为检验都是临时医嘱，临时医嘱的计划开始时间和结束时间是一样的，所以不需要判断计划结束时间
			if(orderInfo.getExecStatus()!=null){
				if(StateEnum.ORDER_INVALID.getValue().equals(String.valueOf(orderInfo.getExecStatus()))){
					throw new RuntimeException("该医嘱已"+StateEnum.ORDER_INVALID.getText());
				}
				if(StateEnum.ORDER_DEL.getValue().equals(String.valueOf(orderInfo.getExecStatus()))){
					throw new RuntimeException("该医嘱已"+StateEnum.ORDER_DEL.getText());
				}
				if(StateEnum.ORDER_CANCEL.getValue().equals(String.valueOf(orderInfo.getExecStatus()))){
					throw new RuntimeException("该医嘱已"+StateEnum.ORDER_CANCEL.getText());
				}
			}

			List<SpecimenNodeInfoVO> nodeInfoVOs = this.specimenMapper.querySpecimenNodeStatus2(orderInfo.getOrderId());
			if(CollectionUtils.isEmpty(nodeInfoVOs)){
				continue;
			}
			SpecimenNodeInfoVO tmpSpecimenNodeInfo = nodeInfoVOs.get(nodeInfoVOs.size() - 1);
			tmpSpecimenNodeInfo.setSpecimenNum(orderInfo.getSpecimenNum());
			tmpSpecimenNodeInfo.setSeNum(orderInfo.getSeNum());
			specimenNodeResult.add(tmpSpecimenNodeInfo);
		}

		return specimenNodeResult;
	}



	@Override
	public SpecimenLabInfoVO queryLabList(String specimenNum) {
		SpecimenLabInfoVO specimenLabInfoVO = new SpecimenLabInfoVO();
		SpecimenDetailVO specimenDetailVO = this.specimenMapper.querySepcimen(specimenNum);
		List<SpecimenLabItemVO> list = this.specimenMapper.querySepcimenLabItem(specimenNum);
		String testTubeColor = specimenMapper.selectSysTestTubeColorBySpecimenNum(specimenNum);
		if(StringUtils.isNotBlank(testTubeColor)){
			specimenDetailVO.setCellColor(testTubeColor);
		}else{
			specimenDetailVO.setCellColor("");
		}
		specimenLabInfoVO.setSpecimenDetail(specimenDetailVO);
		specimenLabInfoVO.setSpecimenLabItemList(list);
		return specimenLabInfoVO;
	}
	/**
	 * 标本的双码校验
	 * @param firstQrCode 第一个条码是腕带
	 * @param secondQrCode 第二个标本标码
	 * @param nodeType
	 * @return
	 */
	@Override
	public SpecimenQrCodeStatusDto<TaskNodeVO> checkSpecimenQrCode(String firstQrCode, String secondQrCode, String nodeType) {
		final  String separator="-";
		final String inpatNum=firstQrCode;
		SpecimenQrCodeStatusDto<TaskNodeVO> result=new SpecimenQrCodeStatusDto<>();
		SpecimenDetailVO specimenDetail = this.querySpecimen(secondQrCode, "0");
		if(Objects.isNull(specimenDetail)){
			result.setSuccess(false);
			result.setMsg("患者信息与医嘱信息不匹配");
			return result;
		}

		if (!Objects.equals(specimenDetail.getInpatNum().split(separator)[0], inpatNum)) {
			result.setSuccess(false);
			result.setMsg("患者信息与医嘱信息不匹配");
			return result;
		}
		//判断是否是采集阶段
		if(specimenDetail.getNodeInfoVOs().stream().allMatch(x->x.getNodeId().equals(SpecimenFlowEnum.SPECIMEN_COLLECT.getNodeId()))){
			PatientInfo patientInfo = new PatientInfo();
			patientInfo.setMedicalNum(specimenDetail.getPatientInfo().get("medicalNum"));
			patientInfo.setBedNo(specimenDetail.getPatientInfo().get("bedNo"));
			patientInfo.setSex(specimenDetail.getPatientInfo().get("sex"));
			patientInfo.setAge(specimenDetail.getPatientInfo().get("age"));
			patientInfo.setPatName(specimenDetail.getPatientInfo().get("patName"));

			List<OrderInfo> orderInfoList = taskExecuteMapper.querySepcimenOrderInfos(specimenDetail.getSpecimenNum(), specimenDetail.getInpatNum());
			TaskNodeVO taskNodeVO = new TaskNodeVO();
			taskNodeVO.setSpecialNodeType(SpecialNodeEnum.SPECIMEN_COLLECT.getValue());
			taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.SPECIMEN_COLLECT.getText());
			taskNodeVO.setQrCode(specimenDetail.getSpecimenNum());
			taskNodeVO.setOrderInfoList(orderInfoList);
			taskNodeVO.setPatientInfo(patientInfo);
			result.setSuccess(true);
			result.setData(taskNodeVO);
			return result;
		}else if(specimenDetail.getNodeInfoVOs().stream().allMatch(x->x.getNodeId().equals(SpecimenFlowEnum.SPECIMEN_DOUBLE_CHECK.getNodeId()))){
			PatientInfo patientInfo = new PatientInfo();
			patientInfo.setMedicalNum(specimenDetail.getPatientInfo().get("medicalNum"));
			patientInfo.setBedNo(specimenDetail.getPatientInfo().get("bedNo"));
			patientInfo.setSex(specimenDetail.getPatientInfo().get("sex"));
			patientInfo.setAge(specimenDetail.getPatientInfo().get("age"));
			patientInfo.setPatName(specimenDetail.getPatientInfo().get("patName"));

			List<OrderInfo> orderInfoList = taskExecuteMapper.querySepcimenOrderInfos(specimenDetail.getSpecimenNum(), specimenDetail.getInpatNum());
			TaskNodeVO taskNodeVO = new TaskNodeVO();
			taskNodeVO.setSpecialNodeType(SpecialNodeEnum.SPECIMEN_DOUBLE_CHECK.getValue());
			taskNodeVO.setSpecialNodeTypeName(SpecialNodeEnum.SPECIMEN_DOUBLE_CHECK.getText());
			taskNodeVO.setQrCode(specimenDetail.getSpecimenNum());
			taskNodeVO.setOrderInfoList(orderInfoList);
			taskNodeVO.setPatientInfo(patientInfo);
			result.setSuccess(true);
			result.setData(taskNodeVO);
			return result;
		}else{
			if(specimenDetail.getNodeInfoVOs().stream().allMatch(x->x.getNodeId().equals(SpecimenFlowEnum.SPECIMEN_READY.getNodeId()))){
				result.setSuccess(false);
				result.setMsg(specimenDetail.getSpecimenNum()+"还未进行标本准备");
				return result;
			}
			result.setSuccess(false);
			result.setMsg(specimenDetail.getSpecimenNum()+"未找到任务节点");
			return result;
		}

	}


	/**
	 * 标本待转运列表
	 */
	public Result queryLabWaitTransfer(int pageNum, int pageSize,String wardId){
		String wholeInpatNum = mealListMapper.queryPatientInfoByWardDeptId(wardId);
		PageHelper.startPage(pageNum, pageSize);
		List<TaskExecuteBatchDTO> list = specimenMapper.queryLabWaitTransfer(null,null,wardId,wholeInpatNum);
		PageInfo<TaskExecuteBatchDTO> pageInfo = new PageInfo<TaskExecuteBatchDTO>(list);
		return ResultGenerator.genOkResult(pageInfo);
	}

	/**
	 * 根据标本条码查询标本转运信息
	 */
	public Result scannSpecimen(String specimenNum){
		if(StringUtils.isNotBlank(specimenNum)){
			List<TaskExecuteBatchDTO> taskExecuteBatchList = specimenMapper.queryLabWaitTransfer(specimenNum,null,null,null);
			if (CollectionUtils.isNotEmpty(taskExecuteBatchList)) {
				return ResultGenerator.genOkResult(taskExecuteBatchList.get(0));
			}
			return ResultGenerator.genFailedResult("标本无转运信息！");
		}
		return ResultGenerator.genFailedResult("未扫到标本条码！");

	}


	/**
	 * 根据标本条码查询标本转运信息
	 */
	@Transactional(rollbackFor = Exception.class)
	public Result confirmTransfer(SpecimenTransferDTO specimenTransferDTO){
		//获取转运人
		String otherExecutePerson = specimenTransferDTO.getOtherExecutePerson();
		//更新TASK_EXECUTE_BATCH表将状态从未执行变成已执行
		String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
		List<Map<String,Object>>  listMap = new ArrayList<>();
		if(CollectionUtils.isNotEmpty(specimenTransferDTO.getTaskExecuteBatchDTOList())){
			for (TaskExecuteBatchDTO taskExecuteBatchDTO : specimenTransferDTO.getTaskExecuteBatchDTOList()) {
				String[] taskBatchIds = taskExecuteBatchDTO.getTaskBatchId().split(",");
				if(taskBatchIds!=null && taskBatchIds.length>0){
					for(String taskBatchId:taskBatchIds){
						Map<String,Object> map= new HashMap<>();
						TaskExecuteBatchEntity ta=specimenMapper.queryTaskExecuteBatchById(taskBatchId);
						//更新转运人
						specimenMapper.updateTaskExecuteBatchById(otherExecutePerson,ta.getTaskBatchId());
						map.put("taskExecuteDetailEntity", ta);
						map.put("userId",userId);
						listMap.add(map);
					}
				}
			}
			patientOrderService.createNextTaskNodeList(listMap,"");
			return ResultGenerator.genOkResult();
		}else{
			return ResultGenerator.genFailedResult("没有扫描过的标本转运数据！");
		}




	}

	/**
	 * 根据标本条码查询标本转运信息
	 */
	public Result queryLabHistoryTransfer(String startDate,String endDate,String keywords,int pageNum, int pageSize,String wardId){
		String wholeInpatNum = mealListMapper.queryPatientInfoByWardDeptId(wardId);
		PageHelper.startPage(pageNum, pageSize);
		List<TaskExecuteBatchDTO> list = specimenMapper.queryLabHistoryTransfer(startDate, endDate,keywords,null,wardId,wholeInpatNum);
		PageInfo<TaskExecuteBatchDTO> pageInfo = new PageInfo<TaskExecuteBatchDTO>(list);
		return ResultGenerator.genOkResult(pageInfo);
	}


	/**
	 * 查看报告接口
	 */
	public Result viewReport(String specimenNum,String reqNum,String serialNumber){
		TaskExecuteBatchDTO patientLabInfo = specimenMapper.queryPatientLabInfo(specimenNum,reqNum.split(","),serialNumber);
		if(patientLabInfo !=null) {
			if(StringUtils.isNotBlank(patientLabInfo.getDeptName())){
				if(patientLabInfo.getDeptName().indexOf("护理单元")>=0){
					patientLabInfo.setDeptName(patientLabInfo.getDeptName().replace("护理单元",""));
				}
			}
			List<PatientLabReportEntity> patientLabReportEntities = specimenMapper.queryPatientLabReportByReqNum(reqNum.split(","),serialNumber);
			PatientLabReportDTO patientLabReportDTO = new PatientLabReportDTO();
			patientLabReportDTO.setPatientLabInfo(patientLabInfo);
			patientLabReportDTO.setLabReportList(patientLabReportEntities);
			return ResultGenerator.genOkResult(patientLabReportDTO);
		}else{
			return ResultGenerator.genFailedResult("没有检验报告！");
		}
	}

	/**
	 * 根据任务频次id查询任务详细
	 */
	public Result querySpecimenTransferDetail(String taskBatchId,String statusFlag){
		List<TaskExecuteBatchDTO> list;
		if(StringUtils.isNotBlank(taskBatchId)) {
			if ("0".equals(statusFlag)) {
				list = specimenMapper.queryLabWaitTransfer(null, taskBatchId.split(","), null,null);
				if (CollectionUtils.isNotEmpty(list)) {
					return ResultGenerator.genOkResult(list.get(0));
				}
			} else if ("1".equals(statusFlag)) {
				list = specimenMapper.queryLabHistoryTransfer(null, null, null, taskBatchId.split(","), null,null);
				if (CollectionUtils.isNotEmpty(list)) {
					return ResultGenerator.genOkResult(list.get(0));
				}
			}
		}
		return ResultGenerator.genFailedResult("未查询此标本运转数据！");
	}
	/**
	 * 根据病区获取护工信息
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Result queryNurseWorkerList(int pageNum,int pageSize,String keyWords){
		PageHelper.startPage(pageNum, pageSize);
		List<SysNurseCareEntity> list = specimenMapper.queryNurseWorkerList(keyWords);
		if(CollectionUtils.isNotEmpty(list)){
			for(SysNurseCareEntity sysNurseCareEntity:list){
				if(StringUtils.isNotBlank(sysNurseCareEntity.getPhoneNum())){
					sysNurseCareEntity.setPhoneNum(sysNurseCareEntity.getPhoneNum().substring(0,3)+"****"+sysNurseCareEntity.getPhoneNum().substring(7));
				}
			}
		}
		PageInfo<SysNurseCareEntity> pageInfo = new PageInfo<SysNurseCareEntity>(list);
		return ResultGenerator.genOkResult(pageInfo);
	}


    public Result saveDoubleCheckLog(DoubleCheckLogEntity doubleCheckLogEntity){
	    if(doubleCheckLogEntity != null){
			//设置医嘱id
			Map<String, String> map = specimenMapper.queryPatientLabSepcimenBySpecimenNum(doubleCheckLogEntity.getSpecimenNum());
			if(map!=null){
				doubleCheckLogEntity.setCheckItem(map.get("specimenName"));
				doubleCheckLogEntity.setInpatorderdataId(map.get("inpatorderdataId"));
			}else{
				return  ResultGenerator.genFailedResult("该标本条码未查询到医嘱数据!");
			}
			String firstCheckerPersonId = doubleCheckLogEntity.getFirstCheckerPersonId();
	    	Date date = new Date();
			doubleCheckLogEntity.setDoubleCheckLogId(UUIDUtil.randomString());
			doubleCheckLogEntity.initAdd();
            doubleCheckLogEntity.setSecondCheckerTime(new Timestamp(date.getTime()));
			//核对状态（1.核对成功 2.核对失败 3.核对中）
			doubleCheckLogEntity.setCheckStatus("3");
			//数据类型(1.标本采集、2.血库领血、3.病区领血、4.临床输血)
			doubleCheckLogEntity.setDataType("1");
			doubleCheckLogEntity.setFirstCheckerPersonId(null);
			specimenMapper.insertDoubleCheckLog(doubleCheckLogEntity);


			UserEntity userEntity = userMapper.queryUserId(doubleCheckLogEntity.getSecondCheckerPersonId());
			UserEntity firstUserEntity = userMapper.queryUserId(firstCheckerPersonId);
			if(userEntity!=null){
				SocketMessageDTO socketMessageDTO = new SocketMessageDTO();
				PushSocketMessage pushSocketMessage = new PushSocketMessage();
				socketMessageDTO.setMsgType("nurseDoubleCheck");
				Map<String, Object> dataMap = new HashMap<>();
				dataMap.put("msg", "护士【"+userEntity.getUserName()+"】已完成协同核对！");
				socketMessageDTO.setData(dataMap);
				pushSocketMessage.setUserIds(new ArrayList<>(Arrays.asList(firstCheckerPersonId+","+doubleCheckLogEntity.getSpecimenNum()+",1,"+firstUserEntity.getUserName())));
				pushSocketMessage.setData(socketMessageDTO);
				HttpClientUtil.sendPost(socketUrl, pushSocketMessage);
			}



        }
        return ResultGenerator.genOkResult();
    }

	public Result checkDoctorDoubleCheckLog(DoubleCheckLogEntity doubleCheckLogEntity){
		if(doubleCheckLogEntity != null){
			String loginName = doubleCheckLogEntity.getLoginName();
			String password = doubleCheckLogEntity.getPassword();
			// 用户名登录
			UserEntity dbUser = userMapper.queryOneUser(loginName);
			if (dbUser == null) {
				return ResultGenerator.genFailedResult("账号["+loginName+"]不存在");
			} else if (StateEnum.EMR_STOP.getValue().equals(dbUser.getLockFlag())) {
				return ResultGenerator.genFailedResult("账号["+loginName+"]被停用");
			} else if (StateEnum.EMR_DEL.getValue().equals(dbUser.getDelFlag())) {
				return ResultGenerator.genFailedResult("账号["+loginName+"]被删除");
			}else if(!"0".equals(dbUser.getPositionFlag())){
				return ResultGenerator.genFailedResult("账号["+loginName+"]不是医生");
			}
			// 验证密码
			if (!verifyPassword(password,dbUser.getUserPwd())) {
				return ResultGenerator.genFailedResult("密码错误");
			}

			Map<String, String> map = specimenMapper.queryPatientLabSepcimenBySpecimenNum(doubleCheckLogEntity.getSpecimenNum());

			if(map!=null){
				doubleCheckLogEntity.setCheckItem(map.get("specimenName"));
				doubleCheckLogEntity.setInpatorderdataId(map.get("inpatorderdataId"));
			}else{
				return  ResultGenerator.genFailedResult("该标本条码未查询到医嘱数据!");
			}
			String firstCheckerPersonId = doubleCheckLogEntity.getFirstCheckerPersonId();
			UserEntity firstUserEntity = userMapper.queryUserId(firstCheckerPersonId);
			Date date = new Date();
			doubleCheckLogEntity.setDoubleCheckLogId(UUIDUtil.randomString());
			//设置医嘱id
			doubleCheckLogEntity.setSecondCheckerPersonId(dbUser.getUserId());
			doubleCheckLogEntity.initAdd();
			doubleCheckLogEntity.setSecondCheckerTime(new Timestamp(date.getTime()));
			//核对状态（1.核对成功 2.核对失败 3.核对中）
			doubleCheckLogEntity.setCheckStatus("3");
			//数据类型(1.标本采集、2.血库领血、3.病区领血、4.临床输血)
			doubleCheckLogEntity.setDataType("1");
			doubleCheckLogEntity.setFirstCheckerPersonId(null);
			specimenMapper.insertDoubleCheckLog(doubleCheckLogEntity);

			SocketMessageDTO socketMessageDTO = new SocketMessageDTO();
			PushSocketMessage pushSocketMessage = new PushSocketMessage();
			socketMessageDTO.setMsgType("doctorDoubleCheck");
			Map<String, Object> dataMap = new HashMap<>();
			dataMap.put("msg", "医生【"+dbUser.getUserName()+"】已完成协同核对！");
			socketMessageDTO.setData(dataMap);
			pushSocketMessage.setUserIds(new ArrayList<>(Arrays.asList(firstCheckerPersonId+","+doubleCheckLogEntity.getSpecimenNum()+",1,"+firstUserEntity.getUserName())));
			pushSocketMessage.setData(socketMessageDTO);
			HttpClientUtil.sendPost(socketUrl, pushSocketMessage);
		}
		return ResultGenerator.genOkResult();
	}

	public boolean verifyPassword(final String rawPassword, final String encodedPassword) {
		return this.passwordEncoder.matches(rawPassword, encodedPassword);
	}

    public Result nurseDoubleCheck(DoubleCheckLogEntity doubleCheckLogEntity){
        try{
            //String userId = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getHeader("zuul_id");
            List<String> specimens = new ArrayList<>();
            specimens.add(doubleCheckLogEntity.getSpecimenNum());
            List<SpecimenNodeInfoVO> nodeStatusList=executeNextNode(specimens,SpecimenFlowEnum.SPECIMEN_DOUBLE_CHECK);
            specimenNodeChange(nodeStatusList);
            //设置信息
            //核对状态（1.核对成功 2.核对失败 3.核对中）
            doubleCheckLogEntity.setCheckStatus("1");
            //doubleCheckLogEntity.setFirstCheckerPersonId(userId);
            doubleCheckLogEntity.setFirstCheckerTime(new Timestamp(new Date().getTime()));
            doubleCheckLogEntity.setDataType("1");
            specimenMapper.updateDoubleCheckLog(doubleCheckLogEntity);
        }catch (Exception ex){
            return  ResultGenerator.genFailedResult(ex.getMessage());
        }
        return ResultGenerator.genOkResult();
    }

	public String selectHspBasicDataValue(String name){
		return specimenMapper.selectHspBasicDataValue(name);
	}

	public int insertSysTestTubeColor(SysTestTubeColorEntity sysTestTubeColorEntity){
		return specimenMapper.insertSysTestTubeColor(sysTestTubeColorEntity);
	}


}
